import numpy
from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify,send_from_directory,session
from flask_session import Session

from werkzeug.utils import secure_filename
from frameworks.utils.JsonResult2 import *
import os
import time

from datetime import timedelta

# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

from frameworks.utils.JsonResult import *
from frameworks.utils.ApiUtil import *
from frameworks.cores.LoadClass import *
from frameworks.cores.Config import *
from frameworks.utils.RedisUtil import *

import json
import json

server = Flask(__name__)

def create_app():
    app = Flask(__name__)
    return app


app = create_app()
app.config['JSON_AS_ASCII']=False
app.config['SESSION_TYPE'] = 'filesystem'

Session(app)

basepath = os.path.join(os.path.dirname(__file__))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)

print(basepath)

jsonResult = JsonResult2()

loader = LoadClass()

@app.route(env+"/",methods=['GET', 'POST'])
def index():
    if session.get("username") != None:
        return render_template('index.html')
    else:
        return render_template("login.html")

@app.route(env+"/login/api",methods=['POST'])
def loginapi():
    quert_json = request.get_data(as_text=True)
    userinfo = json.loads(quert_json)
    session['username'] = userinfo["username"]
    return JsonResult.setOk("登录成功","{}")

@app.route(env+"/logout",methods=['POST'])
def logout():
    del session['username']
    return JsonResult.setOk("注销成功","{}")

@app.route(env+"/serverslist",methods=['GET', 'POST'])
def serverslist():
    con = loader.load("controller.ServersController",request.get_json())
    serverlist = con.run()
    return render_template('servers.html',
                           serverlist=serverlist
                           )

@app.route(env+"/cat",methods=['GET', 'POST'])
def cat():
    name = request.args.get("pagename","cat")
    return render_template(
        name+'.html'
    )

@app.route(env+"/update",methods=['POST'])
def update():
    response = request.get_data(as_text=True)
    rs = loader.load("controller.ServersController", "ServersController", {
        "func": "update",
        "data": json.loads(response)
    })
    return jsonResult.setOk([], "更新成功")

@app.route(env+"/delete",methods=['GET'])
def delete():
    id = request.args.get("id",0)
    print(id)
    rs = loader.load("controller.ServersController", "ServersController", {
        "func": "delete",
        "data": {"id":id}
    })
    return jsonResult.setOk([], "删除成功")

@app.route(env+"/add",methods=['POST'])
def add():
    response = request.get_data(as_text=True)
    rs = loader.load("controller.ServersController", "ServersController", {
        "func": "add",
        "data": json.loads(response)
    })
    return jsonResult.setOk([], "添加成功")

@app.route(env+"/form",methods=['GET', 'POST'])
def form():
    model = request.args.get("model", "school")
    id = request.args.get("id", "0")
    obj = loader.load("controller.ServersController","ServersController",{
        "func":"getRowData",
        "fields":["id","name","province","city","content"],
        "id": id
    })
    fields = loader.load("controller.ServersController","ServersController",{
        "func":"getMap",
        "fields":["id","name","province","city","content"]
    })
    return render_template(
        'form.html',
        obj=obj[0],
        fields=fields
    )

@app.route(env+"/formadd",methods=['GET', 'POST'])
def formadd():
    model = request.args.get("model", "school")
    fields = loader.load("controller.ServersController","ServersController",{
        "func":"getMap",
        "fields":["id","name","province","city","content"]
    })
    return render_template(
        'formadd.html',
        fields=fields
    )

@app.route(env+"/cols",methods=['GET','POST'])
def cols():
    rs = loader.load("controller.ServersController", "ServersController", {
        "func":"getColumns",
        "fields":["id","name","province","city"]
    })
    return jsonResult.setOk(rs,"获取成功")

@app.route(env+"/user",methods=['GET'])
def user():
    num = request.args.get("limit",10)
    page = request.args.get("page",1)
    data = loader.load("controller.ServersController", "ServersController", {
        "func": "getData",
        "fields": ["id", "name", "province", "city"],
        "page": page,
        "num": num,
        "orderfield": "id",
        "asc": "asc"
    })
    return json.dumps(data)

if __name__ == "__main__":
    app.run()
